<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="流程编号">
              <a-input placeholder="请输入流程编号" v-model="queryParam.processKey"></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="活动大类编号">
              <a-input placeholder="请输入活动大类编号" v-model="queryParam.categoriesCode"></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="活动编码">
              <a-input placeholder="请输入活动编码" v-model="queryParam.actCode"></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="活动名称">
              <a-input placeholder="请输入活动名称" v-model="queryParam.actName"></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="审批状态">
              <a-select default-value=""
                        v-decorator="[ 'bpmStatus', {}]"
                        placeholder="请选择审批状态"
                        v-model="queryParam.bpmStatus"
                        :getPopupContainer="(target) => target.parentNode"
                        allowClear>
                <a-select-option value="1">待提交</a-select-option>
                <a-select-option value="2">审批中</a-select-option>
                <a-select-option value="3">审批通过</a-select-option>
                <a-select-option value="4">驳回</a-select-option>
                <a-select-option value="5">流程追回</a-select-option>
                <a-select-option value="6">关闭</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="活动开始时间">
              <j-date
                placeholder="请选择活动开始时间"
                format='YYYY-MM-DD'
                v-decorator="[ 'beginDate', {}]"
                style="width:100%"
                v-model="queryParam.beginDate"
              />
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="活动结束时间">
              <j-date
                placeholder="请选择活动结束时间"
                format='YYYY-MM-DD'
                v-decorator="[ 'endDate', {}]"
                style="width:100%"
                v-model="queryParam.endDate"
              />
            </a-form-item>
          </a-col>

        <template v-if="toggleSearchStatus">
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button @click="addApply" type="primary" icon="plus">提交流程</a-button>
<!--      <a-button type="primary" icon="download" @click="handleExportXls('活动主表')">导出</a-button>-->
<!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
<!--        <a-button type="primary" icon="import">导入</a-button>-->
<!--      </a-upload>-->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->

    <!--流程申请选择-->
    <a-drawer
      title="选择流程" width="33%"
      placement="right"
      :closable="false"
      @close="processModalVisible = false"
      :visible="processModalVisible"
    >
      <a-empty description="无流程可供选择" v-if="activeKeyAll.length==0" />
      <div v-else>
        <a-input-search style="margin-bottom: 10px;width: 200px"
                        placeholder="输入流程名称" @search="onSearchProcess" />
        <a-collapse v-model="activeKey" name="name">
          <a-collapse-panel name="活动" v-for="(value, index)  in activeKeyAll" :header="filterDictText(dictOptions,value)||'未分类'" :key="value">
            <a-list :grid="{ gutter: 10,column:1}" :dataSource="processDataMap[value]">
              <a-list-item slot="renderItem" slot-scope="item">
                <a-card>
                  <div slot="title">
                    <a-row>
                      <a-col span="12" :title="item.name">{{item.name}} </a-col>
                      <a-col span="12" style="text-align: right;">
                        <a href="javascript:void (0)" @click="chooseProcess(item)">发起申请</a>
                      </a-col>
                    </a-row>
                  </div>
                  <b>版本：</b>v.{{item.version}}
                  <br/>
                  <b>说明：</b>{{item.description}}
                </a-card>
              </a-list-item>
            </a-list>
          </a-collapse-panel>
        </a-collapse>
      </div>
    </a-drawer>
    <!--流程表单-->
    <a-modal :title="lcModa.title" v-model="lcModa.visible" :footer="null" :maskClosable="false" width="80%">
      <component :disabled="lcModa.disabled" v-if="lcModa.visible" :is="lcModa.formComponent"
                 :processData="lcModa.processData" :isNew = "lcModa.isNew"
                 :infourl="url.getInfo" :businessid ="lcModa.businessid"
                 @afterSubmit="afterSub" @close="lcModa.visible=false,lcModa.disabled = false"></component>
    </a-modal>
    <!--提交申请表单-->
    <a-modal title="提交申请" v-model="modalVisible" :mask-closable="false" :width="500" :footer="null">
      <div v-if="modalVisible">
        <a-form-item label="选择审批人" v-show="showAssign">
          <a-select style="width: 100%"
                    v-model="form.assignees"
                    placeholder="请选择"
                    mode="multiple"
                    :allowClear="true"
          >
            <a-select-option v-for="(item, i) in assigneeList" :key="i" :value="item.username">{{item.realname}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="下一审批人" v-show="isGateway">
          <a-alert  type="info" showIcon message="分支网关处不支持自定义选择下一审批人，将自动下发给所有可审批人。">，将发送给下一节点所有人</a-alert>
        </a-form-item>
        <a-form-item label="优先级" prop="priority">
          <a-select v-model="form.priority" placeholder="请选择" :allowClear="true" style="width: 100%">
            <a-select-option :value="0">普通</a-select-option>
            <a-select-option :value="1">重要</a-select-option>
            <a-select-option :value="2">紧急</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="消息通知">
          <a-checkbox v-model="form.sendMessage">站内消息通知</a-checkbox>
          <a-checkbox v-model="form.sendSms" disabled>短信通知</a-checkbox>
          <a-checkbox v-model="form.sendEmail" disabled>邮件通知</a-checkbox>
        </a-form-item>
        <div slot="footer">
          <a-button type="text" @click="modalVisible=false">取消</a-button>
          <div style="display:inline-block;width: 20px;"></div>
          <a-button type="primary" :disabled="submitLoading" @click="applySubmit">提交</a-button>
        </div>
      </div>
    </a-modal>
    <a-modal title="审批历史" v-model="modalLsVisible" :mask-closable="false" :width="'80%'" :footer="null">
      <div v-if="modalLsVisible">
        <historicDetail :procInstId="procInstId"></historicDetail>
      </div>
    </a-modal>
    <a-modal title="确认撤回" v-model="modalCancelVisible" :mask-closable="false" :width="500">
      <a-form ref="delForm" v-model="cancelForm" :label-width="70" v-if="modalCancelVisible">
        <a-form-item label="撤回原因" prop="reason">
          <a-input type="textarea" v-model="cancelForm.reason" :rows="4" />
        </a-form-item>
      </a-form>
      <div slot="footer">
        <a-button type="text" @click="modalCancelVisible=false">取消</a-button>
        <a-button type="primary" :disabled="submitLoading" @click="handelSubmitCancel">提交</a-button>
      </div>
    </a-modal>
    <!-- 表单区域 -->
<!--    <sys-check-rule-modal ref="modalForm" @ok="modalFormOk"/>-->

    <tpmAct-modal ref="modalForm" @ok="modalFormOk"></tpmAct-modal>
  </a-card>
</template>

<script>
  import '@/assets/less/TableExpand.less'
  import TpmActModal from './modules/TpmActModal'
  import { PageListMixin } from '@/mixins/PageListMixin'
  import { activitiMixin } from '@/views/activiti/mixins/activitiMixin'
  import SysCheckRuleModal from '@page-modules/SysCheckRuleModal'
  import { postFormAction, getAction,downFile } from '@/api/manage'
  import {initDictOptions, filterDictText} from '@/components/dict/CnDictSelectUtil'
  import JDate from '@comp/cn-form/JDate'
  export default {
    name: "TpmActList",
    mixins:[PageListMixin,activitiMixin],
    components: {
      TpmActModal,
      SysCheckRuleModal,
      JDate
    },
    data () {
      return {
        description: '活动主表管理页面',
        processModalVisible: null,
        activeKeyAll: [],
        activeKey: [],
        processDataMap: {},
        searchProcessKey: null,
        addApplyLoading: false,
        lcModa: {
          title:'',
          disabled:false,
          visible:false,
          formComponent : null,
          isNew : false,
          businessid:'',
        },
        form:{
          priority:0,
          assignees:[],
          sendMessage:true
        },
        modalVisible: false,
        showAssign: false,
        assigneeList: [],
        isGateway: false,
        dictPriority: [],
        submitLoading: false,
        error: "",
        /*审批历史*/
        modalLsVisible: false,
        procInstId: '',
        modalCancelVisible: false,
        cancelForm: {},
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
           },
          {
            title: '流程编号',
            align:"center",
            dataIndex: 'processKey'
          },
          {
            title: '审批状态',
            align:"center",
            dataIndex: 'bpmStatus_dictText'
          },

		   {
            title: '活动编码',
            align:"center",
            dataIndex: 'actCode'
           },
		   {
            title: '活动名称',
            align:"center",
            dataIndex: 'actName'
           },
          {
            title: '申请人账号',
            align:"center",
            dataIndex: 'applyUserBy'
          },
          {
            title: '申请金额',
            align:"center",
            dataIndex: 'amount'
          },
          {
            title: '活动开始时间',
            align:"center",
            dataIndex: 'beginDate'
          },
          {
            title: '活动结束时间',
            align:"center",
            dataIndex: 'endDate'
          },
          {
            title: '申请人姓名',
            align:"center",
            dataIndex: 'applyUserName'
          },
		   {
            title: '是否完成核销',
            align:"center",
            dataIndex: 'auditStatus_dictText'
           },
		   {
            title: '活动大类编号',
            align:"center",
            dataIndex: 'categoriesCode'
           },
		   {
            title: '活动大类名称',
            align:"center",
            dataIndex: 'categoriesName'
           },
          {
            title: '更新时间',
            align:"center",
            dataIndex: 'updateDate'
          },
          {
            title: '更新人姓名',
            align:"center",
            dataIndex: 'updateName'
          },
          {
            title: '停用启用状态',
            align:"center",
            dataIndex: 'status',
            customRender: function (text) {
              if (text === '009') {
                return '启用'
              } else {
                return '停用'
              }
            }
          },
          {
            title: '是否删除',
            align:"center",
            dataIndex: 'deleteStatus',
            customRender: function (text) {
              if (text === '009') {
                return '否'
              } else {
                return '是'
              }
            }
          },
          {
            title: '备注',
            align:"center",
            dataIndex: 'remarks'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            scopedSlots: { customRender: 'action' },
          },
        ],
		url: {
          list:window._CONFIG['domianTpmURL']+ "/act/tpmAct/findPageList",
          delete:window._CONFIG['domianTpmURL']+ "/act/tpmAct/delete",
          deleteBatch:window._CONFIG['domianTpmURL']+ "/act/tpmAct/deleteBatch",
          exportXlsUrl: "act/tpmAct/exportXls",
          importExcelUrl: "act/tpmAct/importExcel",
          getProcessDataList: window._CONFIG['domianTpmURL']+"/activiti_process/listData",
          getInfo:window._CONFIG['domianTpmURL']+"/act/tpmAct/getInfo",
       },
    }
  },
  computed: {
    importExcelUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
    methods: {
      getFormComponent(routeName){
        return _.find(this.allFormComponent,{routeName:routeName})||{};
      },
      millsToTime(mills) {
        if (!mills) {
          return "";
        }
        let s = mills / 1000;
        if (s < 60) {
          return s.toFixed(0) + " 秒"
        }
        let m = s / 60;
        if (m < 60) {
          return m.toFixed(0) + " 分钟"
        }
        let h = m / 60;
        if (h < 24) {
          return h.toFixed(0) + " 小时"
        }
        let d = h / 24;
        if (d < 30) {
          return d.toFixed(0) + " 天"
        }
        let month = d / 30
        if (month < 12) {
          return month.toFixed(0) + " 个月"
        }
        let year = month / 12
        return year.toFixed(0) + " 年"

      },
      addApply() {
        if (this.selectedRowKeys.length != 1) {
          this.$message.warning('请选择一条记录！');
          return;
        }
        this.getProcessList(this.selectionRows)
      },
      submitAct(){

      },
      initDictConfig() {
        //初始化字典 - 流程分类
        initDictOptions('bpm_process_type').then((res) => {
          if (res.success) {
            this.dictOptions = res.result;
          }
        });
      },
      filterDictText(dictOptions, text) {
        if (dictOptions instanceof Array) {
          for (let dictItem of dictOptions) {
            if (text === dictItem.value) {
              return dictItem.text
            }
          }
        }
        return text||text=='null'?'':text
      },
      getProcessList(record) {

        if(record[0].bpmStatus != 1){
          this.$message.warning('访数据不能两次提交流程！');
          return;
        }
        this.lcModa.businessid = record[0].id;
        this.addApplyLoading = true;
        var that = this
        getAction(this.url.getProcessDataList,{status:1,roles:true}).then(res => {
          this.activeKeyAll = [];
          if (res.success) {
            var result = res.result||[];
            if (result.length>0){
              let searchProcessKey = this.searchProcessKey;
              if (searchProcessKey){ //过滤条件
                result = _.filter(result, function(o) { return o.name.indexOf(searchProcessKey)>-1; });
              }
              that.processDataMap = _.groupBy(result,'categoryId');
              for (const categoryId in that.processDataMap) {
                that.activeKeyAll.push(categoryId)
              }
              that.activeKey = this.activeKeyAll;
            }
            that.processModalVisible = true;
          }else {
            that.$message.warning(res.message)
          }
        }).finally(()=>this.addApplyLoading = false);
      },
      cancel(v) {
        this.cancelForm.id = v.id;
        this.cancelForm.procInstId = v.procInstId;
        this.modalCancelVisible = true;
      },
      handelSubmitCancel() {
        this.submitLoading = true;
        postFormAction(this.url.cancelApply,this.cancelForm).then(res => {
          if (res.success) {
            this.$message.success("操作成功");
            this.loadData();
            this.modalCancelVisible = false;
          }else {
            this.$message.error(res.message);
          }
        }).finally(()=>this.submitLoading = false);
      },
      onSearchProcess(value) {
        this.searchProcessKey = value;
        this.getProcessList()
      },
      apply(v) {
        if (!v.procDefId || v.procDefId == "null") {
          this.$message.error("流程定义为空");
          return;
        }
        this.form.id = v.id;
        this.form.procDefId = v.procDefId;
        this.form.title = v.title;
        // 加载审批人
        getAction(this.url.getFirstNode,{procDefId:v.procDefId}).then(res => {
          if (res.success) {
            if (res.result.type == 3 || res.result.type == 4) {
              this.isGateway = true;
              this.modalVisible = true;
              this.form.firstGateway = true;
              this.showAssign = false;
              this.error = "";
              return;
            }
            this.form.firstGateway = false;
            this.isGateway = false;
            if (res.result.users && res.result.users.length > 0) {
              this.error = "";
              this.assigneeList = res.result.users;
              // 默认勾选
              let ids = [];
              res.result.users.forEach(e => {
                ids.push(e.username);
              });
              this.form.assignees = ids;
              this.showAssign = true;
            } else {
              this.form.assignees = [];
              this.showAssign = true;
              this.error = '审批节点未分配候选审批人员，请联系管理员！';
            }
            if (this.error){
              this.$message.error(this.error)
              return;
            }
            this.modalVisible = true;
          }else {
            this.$message.error(res.message)
          }
        });

      },
      applySubmit() {
        if (this.showAssign && this.form.assignees.length < 1) {
          this.error = "请至少选择一个审批人";
          this.$message.error(this.error)
          return;
        } else {
          this.error = "";
        }
        this.submitLoading = true;
        var params = Object.assign({},this.form);
        params.assignees = params.assignees.join(",")
        postFormAction(this.url.applyBusiness,params).then(res => {
          if (res.success) {
            this.$message.success("操作成功");
            this.loadData();
            this.modalVisible = false;
          }else {
            this.$message.error(res.message)
          }
        }).finally(()=>this.submitLoading = false);
      },
      chooseProcess(v) {
        if (!v.routeName) {
          this.$message.warning(
            "该流程信息未配置表单，请联系开发人员！"
          );
          return;
        }
        this.lcModa.formComponent = this.getFormComponent(v.routeName).component;
        this.lcModa.title = '发起流程：'+v.name;
        this.lcModa.isNew = true;
        this.lcModa.processData = v;
        this.lcModa.visible = true;
        this.lcModa.disabled = false;
        console.log("发起",v)
      },
      afterSub(formData){
        this.lcModa.visible = false;
        this.processModalVisible = false;
        this.loadData();
      },

    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>